package cn.jeeweb.web.modules.sys.controller;

import cn.jeeweb.common.http.Response;
import cn.jeeweb.common.mvc.annotation.ViewPrefix;
import cn.jeeweb.common.mybatis.mvc.wrapper.EntityWrapper;
import cn.jeeweb.common.utils.StringUtils;
import cn.jeeweb.web.aspectj.annotation.Log;
import cn.jeeweb.web.modules.sys.entity.*;
import cn.jeeweb.web.modules.sys.service.IOrganizationService;
import cn.jeeweb.web.modules.sys.service.ISysUserGroupService;
import cn.jeeweb.web.modules.sys.service.IUserService;
import cn.xjzn.framework_Core.ModuleActionType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/groupuser")
@ViewPrefix("modules/groupuser")
@Log(title = "sys_group_user")
public class SysUserGroupController {
    @Autowired
    private ISysUserGroupService sysUserGroupService;

    @Autowired
    private IUserService userService;


    @Autowired
    private IOrganizationService organizationService;

    @PostMapping("save")
    @Log(logType = ModuleActionType.INSERT)
    public Response save(String groupId, String[] userIds) {
        if (StringUtils.isNotBlank(groupId)) {
            EntityWrapper<SysUserGroup> entityWrapper = new EntityWrapper<>(SysUserGroup.class);
            entityWrapper.eq("groupId", groupId);
            sysUserGroupService.delete(entityWrapper);
        } else {
            return Response.error("数据格式有误");
        }

        if (userIds != null && userIds.length > 0) {
            for (String userId : userIds) {
                SysUserGroup sysUserGroup = new SysUserGroup();
                sysUserGroup.setGroupId(groupId);
                sysUserGroup.setUserId(userId);
                sysUserGroupService.insert(sysUserGroup);
            }
        }
        return Response.ok("保存成功");
    }

    @PostMapping("getUserIds")
    public Response getUserIds(String groupId) {
        Map map = new HashMap<String, Object>();
        EntityWrapper<SysUserGroup> entityWrapper = new EntityWrapper<>(SysUserGroup.class);
        entityWrapper.eq("groupId", groupId);
        List<SysUserGroup> list = sysUserGroupService.selectList(entityWrapper);
        if (list != null && list.size() > 0) {
            String[] array = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                array[i] = list.get(i).getUserId();
            }
            map.put("record", array);
        }
        return Response.ok("", map);
    }

    @PostMapping("getUsersData")
    public Response getUsersData(String organizationId, String groupId) {
        Map map = new HashMap<String, Object>();
        EntityWrapper<SysUserGroup> entityWrapper = new EntityWrapper<>(SysUserGroup.class);
        entityWrapper.eq("groupId", groupId);
        List<SysUserGroup> list = sysUserGroupService.selectList(entityWrapper);
        String[] array = null;
        if (list != null && list.size() > 0) {
            array = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                array[i] = list.get(i).getUserId();
            }
        }
        map.put("userIds", array);
        List<User> users = userService.getUsersByOrgId(organizationId);
        List<UserVo> userVos = new ArrayList<UserVo>();
        if (users != null && users.size() > 0) {
            for (User user : users) {
                UserVo userVo = new UserVo();
                userVo.setName(user.getRealname());
                userVo.setId(user.getId());
                userVo.setDisabled(false);
                userVos.add(userVo);
            }
        }
        map.put("userData", userVos);
        Map map_ = new HashMap<String, Object>();
        map_.put("record", map);
        return Response.ok("", map_);
    }

    @PostMapping("add")
    @Log(logType = ModuleActionType.INSERT)
    public Response add(String groupId, String[] userIds) {
        if (userIds != null && userIds.length > 0) {
            for (String userId : userIds) {
                SysUserGroup sysUserGroup = new SysUserGroup();
                sysUserGroup.setGroupId(groupId);
                sysUserGroup.setUserId(userId);
                sysUserGroupService.insert(sysUserGroup);
            }
        }
        return Response.ok("添加成功");
    }

    @PostMapping("delete")
    @Log(logType = ModuleActionType.INSERT)
    public Response delete(String groupId, String[] userIds) {
        EntityWrapper<SysUserGroup> entityWrapper = new EntityWrapper<>(SysUserGroup.class);
        entityWrapper.eq("groupId", groupId);
        entityWrapper.in("userId", userIds);
        sysUserGroupService.delete(entityWrapper);
        return Response.ok("删除成功");
    }


    /**
     * 获取组用户信息
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "listGroup")
    @Log(logType = ModuleActionType.SELECT)
    public void listGroup(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<Organization> entityWrapper = new EntityWrapper<Organization>(Organization.class);
        entityWrapper.eq("organizationType", "3");
        List<Organization> organizationList = organizationService.selectList(entityWrapper);
        List<Group> groups = new ArrayList<Group>();
        if(organizationList != null && organizationList.size() > 0){
            for(Organization organization : organizationList){
                String organizationId = organization.getId();
                Group group = new Group();
                List<Group> children = null;
                group.setId(organization.getId());
                group.setName(organization.getName());
                group.setCode(organization.getCode());
                groups.add(group);
                List<User> users = userService.getUsersByGroupId(organization.getId());
                if(users != null && users.size() > 0){
                    children = new ArrayList<Group>();
                    for(User user : users){
                        Group group_ = new Group();
                        group_.setId(user.getId());
                        group_.setName(user.getRealname());
                        group_.setCode(user.getCode());
                        group_.setParentId(organizationId);
                        children.add(group_);
                    }
                    group.setChildren(children);
                }
            }
        }
        String content = JSON.toJSONString(groups, SerializerFeature.WriteMapNullValue);
        StringUtils.printJson(response, content);
    }


    @PostMapping("getUsersByGroupId")
    public Response getUsersByGroupId(String groupId) {
        List<User> users = userService.getUsersByGroupId(groupId);
        List<UserVo> userVos = new ArrayList<UserVo>();
        if (users != null && users.size() > 0) {
            for (User user : users) {
                UserVo userVo = new UserVo();
                userVo.setName(user.getRealname());
                userVo.setId(user.getId());
                userVo.setDisabled(false);
                userVos.add(userVo);
            }
        }
        Map map_ = new HashMap<String, Object>();
        map_.put("record", userVos);
        return Response.ok("", map_);
    }

}